package com.shuang.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shuang.common.JsonUtils;
import com.shuang.pojo.DbReceiveInformation;
import com.shuang.pojo.DbUser;
import com.shuang.pojo.TempDbOrder;
import com.shuang.redis.JedisClient;
import com.shuang.service.DbOrderService;
import com.shuang.service.DbReceiveInformationService;
import com.shuang.service.DbUserService;
/**
 * 前台用户要登陆才能做的操作
 * @author shuang
 *
 */
@Controller
@RequestMapping("/operation")
public class UserOperationHanlder {
	@Resource(name="dbReceiveInformationService")
	private DbReceiveInformationService dbReceiveInformationService;
	
	@Resource(name="jedisClient")
	private JedisClient jedisClient;
	
	@Value("${REDIS_ORDER_KEY}")
	private String REDIS_ORDER_KEY;
	
	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY ;
	
	@Resource(name="dbOrderService")
	private DbOrderService dbOrderService;
	
	@Resource(name="dbUserService")
	private DbUserService dbUserService;
	
	@RequestMapping("/purchase")
	public String  purchase(){
		System.out.println("进来了");
				return "500";
	}
	@RequestMapping("/addAddress")
	@ResponseBody
	public Map<String,Object> zipCode(DbReceiveInformation dbReceiveInformation ,HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		DbUser dbUser=(DbUser)getFrontUserInfoByToken(cookies);
		dbReceiveInformation.setuId(dbUser.getuId());
		return dbReceiveInformationService.saveInformation(dbReceiveInformation);
	}
	@RequestMapping("/updateAddress")
	@ResponseBody
	public Map<String,Object>  updateAddress(Long oId,Long riId ,HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		try {
			Cookie[] cookies = request.getCookies();
			DbUser dbUser=(DbUser)getFrontUserInfoByToken(cookies);
			String orderStr=jedisClient.hget(REDIS_ORDER_KEY, oId.toString());
			TempDbOrder tempDbOrder=JsonUtils.jsonToPojo(orderStr, TempDbOrder.class);
			if(tempDbOrder.getoId().longValue()==oId.longValue()&&tempDbOrder.getuId().longValue()==dbUser.getuId().longValue()){
				DbReceiveInformation dbReceiveInformation=dbReceiveInformationService.getReceiveInfomationByRiId(riId);
				tempDbOrder.setRiInfo(dbReceiveInformation.getRiAddress()+" "+dbReceiveInformation.getRiName()+" "+dbReceiveInformation.getRiPhone()+" "+dbReceiveInformation.getRiZipCode());
			}
			jedisClient.hset(REDIS_ORDER_KEY, oId.toString(), JsonUtils.objectToJson(tempDbOrder));
			jedisClient.expire(oId.toString(), 1800);
			map.put("status", 200);
		} catch (Exception e) {
			map.put("status", 500);
			e.printStackTrace();
		}
		return map;
	}
	@RequestMapping("/orderTrade")
	@ResponseBody
	public Map<String,Object> orderTrade(Long orderId,String buyMsg ){
		Map<String,Object> map=new HashMap<String, Object>();
		if(orderId==null){
			map.put("status", 403);
			map.put("data", "订单信息错误");
			return map;
		}
		try {
			map = dbOrderService.createOrder(orderId,buyMsg);
		} catch (Exception e) {
			map.put("status", 500);
			map.put("data", "订单生成错误");
			e.printStackTrace();
		}
		return map;
	}
	@RequestMapping("/updateTelById")
	@ResponseBody
	public Map<String,Object> updateTelById(String tel,String mail ,HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		DbUser dbUser=(DbUser)getFrontUserInfoByToken(cookies);
		
		if(dbUser==null||tel==null||tel==""||mail==null||mail==""){//为空判断与登陆与否判断
			map.put("status", 404);
			map.put("data", "操作非法");
			return map;
		}
		
		if(!dbUser.getuPhone().equals(tel)){
			Map<String, Object> result = dbUserService.checkData(tel, "3");
			if((int)result.get("status")!=200){//手机号码验证码
				map.put("status", 403);
				map.put("data", "手机号码已经被使用！");
				return map;
			}
		}
		if(!dbUser.getuEmail().equals(mail)){
			Map<String, Object> result1 = dbUserService.checkData(mail, "2");
			if((int)result1.get("status")!=200){//邮箱验证
				map.put("status", 403);
				map.put("data", "该邮箱已经被使用！");
				return map;
			}
		}
		
		DbUser dbUserTemp=new DbUser();
		dbUserTemp.setuId(dbUser.getuId());
		dbUserTemp.setuPhone(tel);
		dbUserTemp.setuEmail(mail);
		
		int result3 = dbUserService.updateUserSelectiveByPrimaryKey(dbUserTemp);
		if(result3>0){
			map.put("status", 200);
			map.put("data", "修改成功");
		}else{
			map.put("status", 500);
			map.put("data", "修改错误");
		}
		return map;
	}
	
	@RequestMapping("/updatePwdById")
	@ResponseBody
	public Map<String,Object> updatePwdById(String pwd,String rpwd,HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		Cookie[] cookies = request.getCookies();
		DbUser dbUser=(DbUser)getFrontUserInfoByToken(cookies);
		
		if(dbUser==null||pwd.length()<6||pwd.length()>20){
			map.put("status", 404);
			map.put("data", "操作非法");
			return map;
		}
		if(!pwd.equals(rpwd)){
			map.put("status", 403);
			map.put("data", "密码输入不一致");
			return map;
		}
		DbUser dbUserTemp=new DbUser();
		dbUserTemp.setuId(dbUser.getuId());
		dbUserTemp.setuPwd(DigestUtils.md5DigestAsHex(pwd.getBytes()));
		int result3 = dbUserService.updateUserSelectiveByPrimaryKey(dbUserTemp);
		if(result3>0){
			map.put("status", 200);
			map.put("data", "修改成功");
		}else{
			map.put("status", 500);
			map.put("data", "修改错误");
		}
		return map;
	}
	/**
	 * 前台用户信息获取
	 * @param cookies
	 * @return
	 */
	private Object getFrontUserInfoByToken(Cookie[] cookies){
		if(cookies!=null&&cookies.length>0){
			for(Cookie cookie:cookies){
				if(cookie.getName().equals("FRONT_SESSION_KEY")){
					String token=cookie.getValue();
					System.out.println(token);
					String userInfoString=jedisClient.get(REDIS_USER_SESSION_KEY+":"+token);//获取用户的信息
					if(userInfoString!=null&&userInfoString!=""){
						return JsonUtils.jsonToPojo(userInfoString,DbUser.class);//用户登陆过了传过去页面的信息
					}
				}
			}
		}
		return null;
	}
}
